package com.cnfol.emoj.util;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import com.cnfol.emoj.adapter.EmotionGridViewAdapter;
import net.tsz.afinal.json.JsonMap;
import so.shanku.essential.R;

import java.util.ArrayList;

/**
 * @author : LXM
 * @date :2015-6-10 下午1:45:45
 * @detail :聊天底部
 */
public class InitChatBottomUtils {
    private Context context;
    private OnClickListener listener;
    /**
     * 键盘 是否显示
     */
    public boolean isOpen = false;
    private GetEdContent getEdContent;

    private View root;
    private RadioGroup radioGroup;
    private ImageView keyBoard;
    private LinearLayout emoView;
    private ImageView emotionImage;
    private EditText editText;
    private ViewPager emotionVp;
    private ArrayList<GridView> gridViews = new ArrayList<GridView>();

    private InputMethodManager manager;

    /**
     * 表情集合
     */
    public static ArrayList<JsonMap<String, Object>> emojis = new ArrayList<JsonMap<String, Object>>();

    /**
     * 页数
     */
    private int pageSize = 0;

    /**
     * 每页表情个数
     */
    private int pageCount = 21;

    public InitChatBottomUtils(Context context, View root,
                               OnClickListener btnSendClickListener, GetEdContent getEdContent) {
        super();
        this.context = context;
        this.root = root;
        this.listener = btnSendClickListener;
        this.getEdContent = getEdContent;
        manager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        mInitEmotion();
    }

    /**
     * 设置编辑框
     *
     * @param editText
     */
    public void setEditText(EditText editText) {
        this.editText = editText;
        closeEmojBoard();
    }

    private void mInitEmotion() {

        keyBoard = (ImageView) root.findViewById(R.id.soft_arror_iv);
        keyBoard.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    hidenKeyBoard();
                } else {
                    openKeyBoard();
                }
                closeEmojBoard();
            }

        });

        emoView = (LinearLayout) root.findViewById(R.id.live_express_view);
        emoView.setVisibility(View.GONE);
        emotionImage = (ImageView) root.findViewById(R.id.emoji_iv);
        emotionImage.setOnClickListener(new OnClickListener() {// 打开表情

            @Override
            public void onClick(View v) {
                if (isOpen) {
                    hidenKeyBoard();
                }
                openEmojBoard();
            }

        });

        emotionVp = (ViewPager) root.findViewById(R.id.live_viewpager);

        initGradViews();// 初始化表情布局；
        initEmotionVp();

    }

    /**
     * 初始化GradView
     */
    private void initGradViews() {
        gridViews = new ArrayList<GridView>();
        LayoutInflater inflater = LayoutInflater.from(context);
        gridViews.clear();
        int pageSize = emojis.size() / pageCount;
        pageSize = emojis.size() % pageCount == 0 ? pageSize : (pageSize + 1);
        for (int i = 0; i < pageSize; i++) {
            final int index = i;
            GridView gridView1 = (GridView) inflater.inflate(
                    R.layout.fragment_news_detail_emotin_gridview, null, false);
            EmotionGridViewAdapter emotionGridViewAdapter = new EmotionGridViewAdapter(
                    context);
            int endIndex = (i + 1) * pageCount < emojis.size() ? (i + 1)
                    * pageCount : emojis.size();
            int startIndex = i * pageCount;
            ArrayList<JsonMap<String, Object>> subList = new ArrayList<JsonMap<String, Object>>();// =
            // (ArrayList<JsonMap<String,
            // Object>>)
            // emojis.subList(i,
            // endIndex);
            for (int j = startIndex; j < endIndex; j++) {
                subList.add(emojis.get(j));
            }
            emotionGridViewAdapter.setDatas(subList);
            gridView1.setAdapter(emotionGridViewAdapter);// ,
            // gridViews.subList(i,i*pageCount)
            // ));
            gridViews.add(gridView1);
            gridView1.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    // if (arg2 == 20 || arg2 == 40 || arg2 == 60 || arg2 == 80
                    // || arg2 == 100 || (j == 5 && arg2 == 5)) {
                    // int selectionStart = sendEd.getSelectionStart();
                    // String text = sendEd.getText().toString();
                    //
                    // if (!TextUtils.isEmpty(text)) {
                    // String body = sendEd.getText().toString();
                    // String tempStr = body.substring(0, selectionStart);
                    // int i = tempStr.lastIndexOf("]");// 获取最后一个表情的位置
                    // if (i == tempStr.length() - 1) {// 说明光标刚好停在这个表情之后
                    // int j = tempStr.lastIndexOf("[");// 将这两个之间的字符删掉
                    // sendEd.getEditableText().delete(j, selectionStart);
                    // } else {
                    // sendEd.getEditableText().delete(
                    // tempStr.length() - 1, selectionStart);
                    // }
                    // }
                    //
                    // } else {
                    JsonMap jsonMap = emojis.get(arg2 + index * pageCount);
                    String idStr = jsonMap.getStringNoNull("code");
                    String emotionString = ExpressionUtil2
                            .generaterEmojStr(idStr);// [arg2+j*20];
                    String text = editText.getText().toString() + emotionString;
                    SpannableString spannableString = ExpressionUtil2
                            .getSpannableString(text, context);
                    editText.setText(spannableString);
                    Editable b = editText.getText();
                    editText.setSelection(b.length());
                    // }
                }
            });
        }
    }

    private class EmoitonPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return gridViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(gridViews.get(position));
            return gridViews.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(gridViews.get(position));
        }

    }

    public void initEmotionVp() {
        radioGroup = (RadioGroup) root.findViewById(R.id.radioGroup1);
        emotionVp.setAdapter(new EmoitonPagerAdapter());
        radioGroup.removeAllViews();
        for (int i = 0; i < gridViews.size(); i++) {
            RadioButton tempButton = new RadioButton(context);
            // tempButton.setBackgroundResource(R.drawable.vp_bottom_selector);
            // // 设置RadioButton的背景图片
            tempButton.setButtonDrawable(R.drawable.rb_db_selector);
            radioGroup.addView(tempButton);
        }
        if (radioGroup.getChildCount() > 0) {
            RadioButton rb = (RadioButton) radioGroup.getChildAt(0);
            rb.setChecked(true);
        }
        emotionVp.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                RadioButton rb = (RadioButton) radioGroup.getChildAt(arg0);
                rb.setChecked(true);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        emotionVp.setOffscreenPageLimit(pageSize);
    }

    public void initEmotionVp(ArrayList<JsonMap<String, Object>> datas) {
        emojis = datas;
        initGradViews();
        initEmotionVp();
    }

    public void openKeyBoard() {
        isOpen = true;
        keyBoard.setSelected(isOpen);
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        // 得到InputMethodManager的实例
        if (imm.isActive()) {
            // 如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);
            // 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    /**
     * 隐藏软键盘
     */
    public void hidenKeyBoard() {
        isOpen = false;
        keyBoard.setSelected(isOpen);
        if (((Activity) context).getCurrentFocus() != null) {
            ((InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(((Activity) context)
                                    .getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }

    /**
     * 表情是否在显示
     *
     * @return
     */
    public boolean isEmojiShow() {
        return emoView.getVisibility() == View.VISIBLE;
    }

    /**
     * 消息发送时，隐藏表情框 和键盘
     */
    public void hideESLayout() {
        isOpen = false;
        closeEmojBoard();
        hidenKeyBoard();
    }

    /**
     * 打开表情
     */
    public void openEmojBoard() {
        isOpen = false;
        hidenKeyBoard();
        emoView.setVisibility(View.VISIBLE);
    }

    /**
     * 关闭表情
     */
    public void closeEmojBoard() {
        emoView.setVisibility(View.GONE);
    }

    /**
     * 设置键盘状态
     *
     * @param bool
     */
    public void setKeyBoardState(boolean bool) {
        if (isOpen) {
            openKeyBoard();
        } else {
            closeEmojBoard();
        }
        isOpen = bool;
        keyBoard.setSelected(isOpen);
    }

    /**
     * @author LXM
     * @date 2015-6-10
     * @detail :获取EditText中的内容
     */
    public interface GetEdContent {
        void getEdContent(String content);
    }
}
